/**
 * websocket server
 * @type {Http2Server | Server}
 * @link https://socket.io/docs/
 */
const app = require('http').createServer(handler)
const io = require('socket.io')(app);
const fs = require('fs');
const redis = require("redis");
const env = require("dotenv").config().parsed;
const client = redis.createClient(env.redis_port, env.redis_host);
client.on("error", function (error) {
  console.error(error);
});

client.subscribe(env.channel)

client.on("message", function (channel, message) {
  console.log("Subscriber received message in channel '" + channel + "': " + message);
  io.emit('news', message);
});

app.listen(env.port);

function handler(req, res) {
  // Set CORS headers
	res.setHeader('Access-Control-Allow-Origin', '*');
	res.setHeader('Access-Control-Request-Method', '*');
	res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
	res.setHeader('Access-Control-Allow-Headers', '*');
  res.end('hi')
}

io.on('connection', (socket) => {
  console.log('client coming...')
});